﻿#region Header

/*
Remote views based on linq
By

Pascal Hauser 
Dipl. Ing. in Informatik, Hochschule für Technik Rapperswil, 2006
Master Thesis, Hochschule für Technik Rapperswil, 2008-2010

and

Raphael Gfeller
Dipl. Ing. in Informatik, Hochschule für Technik Rapperswil, 2006
Master Thesis, Hochschule für Technik Rapperswil, 2008-2010

*/

#endregion

#region Usings

using System;
using System.Threading;
using InterLinq.Types;
using Sebarf.Core.Interfaces;
using Sebarf.Services.Interfaces;
using Sebarf.Utils.Interfaces;
using Sebastof.Services.Interfaces;
using Utils;

#endregion

namespace Sebastof.ProcessChains.ProcessSteps {
	/// <summary>
	/// This is another processing step (for single objects).
	/// Every object transfered will here be put into a lookup table (id->object | object->id).
	/// </summary>
	public class CollectionMapperStep : ProcessStep<CollectionTransporter> {
		#region Public Properties

		[ServiceRequest]
		public IServiceLocatorService ServiceLocatorService { get; set; }

		[ServiceRequest]
		public IObjectMappingRegisterService ObjectMappingRegisterService { get; set; }

		[ServiceRequest]
		public IObjectHierarchyFlattenerService ObjectHierarchyFlattenerService { get; set; }

		#endregion

		#region Public Methods

		public CollectionMapperStep(IServiceLocatorService m) {
			ServiceLocatorService = m;
			ObjectMappingRegisterService = m.GetRegisteredService<IObjectMappingRegisterService>();
		}

		public CollectionMapperStep() {
		}

		protected override CollectionTransporter OnProcess(CollectionTransporter toProcess) {
			Monitor.Enter(ObjectMappingRegisterService);
			foreach (object o in toProcess.Values) {
				foreach (object nestedo in ObjectHierarchyFlattenerService.Flatten(o)) {
					string key = toProcess.TransferedMetadata.GetMetadata(nestedo, "UniqueIdentifier", Guid.NewGuid().ToString());
					ObjectMappingRegisterService.AddMapping(key, nestedo);
				}
			}
			Monitor.Exit(ObjectMappingRegisterService);
			return base.OnProcess(toProcess);
		}

		#endregion
	}
}